import 'dart:convert';
import 'dart:io';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/screenutil.dart';
import 'package:geolocator/geolocator.dart';
import 'package:image_picker/image_picker.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:shop/config/config.dart';
import 'package:shop/http/HttpUtil.dart';
import 'package:shop/route/my_route.dart';

import 'ServiceEdit.dart';

class MerchantSetting extends StatefulWidget {
  MerchantSetting({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MerchantSetting createState() => _MerchantSetting();
}

class _MerchantSetting extends State<MerchantSetting> {

  String merchantID="";         //商户ID
  dynamic merchant={};          //商户信息
  bool isLogin=false;           //是否登录
  var tu;                       //店铺logo
  List tuList=[];               //存放图片的集合
  String  startTime="00:00:00";    //起始时间
  String  endTime="00:00:00";     //结束时间

  SharedPreferences prefs;
  TextEditingController _merchantName;
  TextEditingController _phone;
  TextEditingController _jieshao;
  TextEditingController _tousuphone;

  // 构造方法
  _MerchantSetting() {
    _getMerchantInfo();
  }

  // 获取店铺信息
  void _getMerchantInfo () async {
    // 获取内存存储的用户id
    prefs = await SharedPreferences.getInstance();
    if(prefs.getBool("isLogin")){
      merchantID = prefs.getString("merchantID");
      var x = await HttpUtil().get("/waimai/merchant/selectMerchantGoods?mId="+merchantID);//根据商户ID查询商户详情
      if(x['code']==200){
        merchant=x['data']['merchant'];
        _merchantName=TextEditingController(text: merchant['mname']);
        _phone=TextEditingController(text: merchant['phone']);
        _jieshao=TextEditingController(text: merchant['jianjie']);
        _tousuphone=TextEditingController(text: merchant['tousuPhone']);
        tu=merchant['picture'];
        List pictureList=x['data']['merchantPictureList'];
        for(int a=0;a<pictureList.length;a++){
          tuList.add(pictureList[a]['picture']);
        }
        var peisongTime=merchant['peisongTime'];
        int index=peisongTime.toString().indexOf("-")+1;
        startTime=peisongTime.toString().substring(0,index-1);
        endTime=peisongTime.toString().substring(index,peisongTime.toString().length);
      }
      setState(() {});
    }
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.init(context , width: 464 , height: 820) ;
    return Scaffold(
      appBar: AppBar(
        title: Text("修改店铺"),
        actions: [
          IconButton(icon: Icon(Icons.pin_drop_outlined), onPressed: (){
            showDialog<Null>(
              context: context,
              barrierDismissible: false,
              builder: (BuildContext context) {
                return new AlertDialog(
                  title: new Text('定位更新'),
                  content: Text('确定把当前定位设置为店铺位置吗？'),
                  actions: <Widget>[
                    new FlatButton(
                      child: new Text('取消'),
                      onPressed: (){
                        MyRoute.pop();
                      },
                    ),
                    new FlatButton(
                        child: new Text('确定'),
                        onPressed: () async{
                          final GeolocatorPlatform _geolocatorPlatform = GeolocatorPlatform.instance;
                          final position =  _geolocatorPlatform.getCurrentPosition().then((value){
                            print(value); //Latitude: 37.4219983, Longitude: -122.084
                            Fluttertoast.showToast(
                            msg: "更新成功",);
                          });

                          MyRoute.pop();
                        }
                    ),
                  ],
                );
              },
            ).then((val) {
              print(val);
            });
          })
        ],
      ),
      body: Column(
          children: [
            Expanded(child: ListView(
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Row(children: [Text("*",style: TextStyle(color: Colors.red),),Text("店铺名称"),SizedBox(width: 5,),],) ,
                    SizedBox(width: 30,),
                    Expanded(
                        child: TextFormField(
                          controller: _merchantName,
                          decoration: InputDecoration(
                              hintText: "请输入店铺名称",
                              hintStyle: TextStyle(fontSize: 14)
                            // border: InputBorder.none,
                          ),
                      )
                    )
                  ],
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Row(children: [Text("*",style: TextStyle(color: Colors.red),),Text("联系电话"),SizedBox(width: 5,),],) ,
                    SizedBox(width: 30,),
                    Expanded(child: TextFormField(
                      controller: _phone,
                      decoration: InputDecoration(
                          hintText: "联系电话方便骑手或用户联系",
                          hintStyle: TextStyle(fontSize: 14)
                        // border: InputBorder.none,
                      ),
                    )
                    )
                  ],
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Row(children: [Text("*",style: TextStyle(color: Colors.red),),Text("投诉电话"),SizedBox(width: 5,),],) ,
                    SizedBox(width: 30,),
                    Expanded(child: TextFormField(
                      controller: _tousuphone,
                      decoration: InputDecoration(
                          hintText: "投诉电话",
                          hintStyle: TextStyle(fontSize: 14)
                        // border: InputBorder.none,
                      ),
                    )
                    )
                  ],
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Row(children: [Text("*",style: TextStyle(color: Colors.red),),Text("店铺介绍"),SizedBox(width: 5,),],) ,
                    SizedBox(width: 30,),
                    Expanded(child: TextFormField(
                      controller: _jieshao,
                      maxLines: 2,
                      decoration: InputDecoration(
                          hintText: "请输入店铺介绍",
                          hintStyle: TextStyle(fontSize: 14)
                        // border: InputBorder.none,
                      ),
                    ))
                  ],
                ),
                // Row(
                //   mainAxisAlignment: MainAxisAlignment.spaceBetween,
                //   children: [
                //     Row(children: [Text("*",style: TextStyle(color: Colors.red),),Text("库存每天填满"),SizedBox(width: 5,),],) ,
                //     SizedBox(width: 10,),
                //     CupertinoSwitch(value: true,onChanged: (v){},)
                //   ],
                // ),
                SizedBox(height: 5,),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Row(children: [Text("*",style: TextStyle(color: Colors.red),),Text("营业时间"),SizedBox(width: 5,),],) ,
                    SizedBox(width: 10,),
                    Expanded(child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceAround,
                      children: [
                        GestureDetector(
                          child: Row(children: [Text(startTime),Icon(Icons.arrow_drop_down)],),
                          onTap: () async {
                            var result = await showTimePicker(
                                context: context,
                                initialTime: TimeOfDay(hour: 0, minute: 0),
                            );
                            if(result!=null){
                              setState(() {
                                startTime=result.hour.toString().padLeft(2,"0")+":"+result.minute.toString().padLeft(2,"0")+":00";
                              });
                            }
                          },
                        ),
                        Text("至"),
                        GestureDetector(
                          child: Row(children: [Text(endTime),Icon(Icons.arrow_drop_down)],),
                          onTap: () async {
                            print(44);
                            var result = await showTimePicker(
                                context: context,
                                initialTime: TimeOfDay(hour: 0, minute: 0)
                            );
                            if(result!=null){
                              setState(() {
                                endTime=result.hour.toString().padLeft(2,"0")+":"+result.minute.toString().padLeft(2,"0")+":00";
                              });
                            }
                          },
                        )
                      ],
                    ),
                    )
                  ],
                ),
                Row(
                  children: [
                    Container(
                      width: ScreenUtil().setWidth(110),
                      child: Row(
                        children: [Text("*",style: TextStyle(color: Colors.red)),Text("店铺LOGO"),SizedBox(width: 5,),],
                      )
                    ),
                    SizedBox(width: 20,),
                    GestureDetector(child: Row(
                      children: [
                        tu==null?Text(""): _ImageView(tu),
                        tu!=null?Text(""): Container(
                          width: 75,
                          height: 80,
                          decoration: BoxDecoration(
                            border: Border.all(color: Colors.black , width: 0) ,
                          ),
                          child: Center(child: Text("+",style: TextStyle(fontSize: 30),),),
                        ),
                      ],
                    ),onTap: () async {
                      var s = await ImagePicker.pickImage(source: ImageSource.gallery);
                      File file = new File(s.path);// 获取文件路径
                      var res = await HttpUtil().upload("/upload", file);
                      tu = res['data'];
                      setState(()  {

                      });
                    },),
                  ],
                ),
                SizedBox(height: 10,),
                Row(
                  children: [
                    Row(children: [Text("*",style: TextStyle(color: Colors.red)),Text("店铺图片"),SizedBox(width: 5,)],),
                    SizedBox(width: 30,),
                    Expanded(child: Wrap(
                      children: [
                        Wrap(
                            spacing: 5,
                            runSpacing: 5,
                            children: _ImageFor(tuList)
                        ),
                        Container(
                          padding: EdgeInsets.fromLTRB(0, 10, 0, 0),
                          child:
                          tuList.length>=5 ? Text("") :
                          GestureDetector(child: Row(
                            children: [
                              Container(
                                width: 75,
                                height: 80,
                                decoration: BoxDecoration(
                                  border: Border.all(color: Colors.black , width: 0) ,
                                ),
                                child: Center(child: Text("+",style: TextStyle(fontSize: 30),),),
                              ),
                            ],
                          ),onTap: () async {
                            var s = await ImagePicker.pickImage(source: ImageSource.gallery);
                            File file = new File(s.path);// 获取文件路径
                            var res = await HttpUtil().upload("/upload", file);
                            print(res['data']);
                            tuList.add(res['data']);
                            setState(()  {

                            });
                          },),
                        ),
                      ],
                    ))
                  ],
                ),
              ],
            )
            ),
            Row(
              children: [
                Expanded(
                    child: GestureDetector(
                      child: Container(
                        color: Colors.red,
                        padding: EdgeInsets.symmetric(vertical: 10),
                        child: Center(
                          child: Text("保存",style: TextStyle(color: Colors.white),),
                        ),
                      ),onTap: () async {
                        if(_merchantName.text.toString()==null || _merchantName.text.toString()==""){
                          Fluttertoast.showToast(
                              msg: "请填写店铺名称",
                              toastLength: Toast.LENGTH_SHORT,
                              gravity: ToastGravity.BOTTOM,
                              timeInSecForIosWeb: 1,
                              backgroundColor: Colors.black45,
                              textColor: Colors.white,
                              fontSize: 16.0
                          );
                          return ;
                        }
                        if(_phone.text.toString()==null || _phone.text.toString()==""){
                          Fluttertoast.showToast(
                              msg: "请填写联系电话",
                              toastLength: Toast.LENGTH_SHORT,
                              gravity: ToastGravity.BOTTOM,
                              timeInSecForIosWeb: 1,
                              backgroundColor: Colors.black45,
                              textColor: Colors.white,
                              fontSize: 16.0
                          );
                          return ;
                        }
                        if(_jieshao.text.toString()==null || _jieshao.text.toString()==""){
                          Fluttertoast.showToast(
                              msg: "请填写店铺介绍",
                              toastLength: Toast.LENGTH_SHORT,
                              gravity: ToastGravity.BOTTOM,
                              timeInSecForIosWeb: 1,
                              backgroundColor: Colors.black45,
                              textColor: Colors.white,
                              fontSize: 16.0
                          );
                          return ;
                        }
                        if(_tousuphone.text.toString()==null || _tousuphone.text.toString()==""){
                          Fluttertoast.showToast(
                              msg: "请填写投诉电话",
                              toastLength: Toast.LENGTH_SHORT,
                              gravity: ToastGravity.BOTTOM,
                              timeInSecForIosWeb: 1,
                              backgroundColor: Colors.black45,
                              textColor: Colors.white,
                              fontSize: 16.0
                          );
                          return ;
                        }
                        if(tu==null || tu==""){
                          Fluttertoast.showToast(
                              msg: "请选择店铺logo",
                              toastLength: Toast.LENGTH_SHORT,
                              gravity: ToastGravity.BOTTOM,
                              timeInSecForIosWeb: 1,
                              backgroundColor: Colors.black45,
                              textColor: Colors.white,
                              fontSize: 16.0
                          );
                          return ;
                        }
                        if(tuList.length<=0){
                          Fluttertoast.showToast(
                              msg: "请选择店铺图片",
                              toastLength: Toast.LENGTH_SHORT,
                              gravity: ToastGravity.BOTTOM,
                              timeInSecForIosWeb: 1,
                              backgroundColor: Colors.black45,
                              textColor: Colors.white,
                              fontSize: 16.0
                          );
                          return ;
                        }
                        String peisongTime=startTime+"-"+endTime;
                        var x = await HttpUtil().get("/waimai/merchant/updateMerchant?mid=${merchantID}&mName=${_merchantName.text.toString()}&phone=${_phone.text.toString()}&jianjie=${_jieshao.text.toString()}&picture=${tu}&peisongTime=${peisongTime}&tousuPhone=${_tousuphone.text.toString()}");//根据商户ID查询商户详情
                        if(x['code']==200){
                          var url="/waimai/merchant/updateMerchantPicture?mid="+merchantID;
                          for(int a=0;a<tuList.length;a++){
                            url=url+"&image${a.toString()}=${tuList[a]}";
                          }
                          var y= await HttpUtil().get(url);
                          print(y);
                          if(y['code']==200){
                            Fluttertoast.showToast(
                                msg: "保存成功",
                                toastLength: Toast.LENGTH_SHORT,
                                gravity: ToastGravity.BOTTOM,
                                timeInSecForIosWeb: 1,
                                backgroundColor: Colors.black45,
                                textColor: Colors.white,
                                fontSize: 16.0
                            );
                            Map map=new Map();
                            map['merchantName']=_merchantName.text.toString();
                            map['icon']=tu;
                            MyRoute.pop(map);
                          }else{
                            Fluttertoast.showToast(
                                msg: "图片保存失败",
                                toastLength: Toast.LENGTH_SHORT,
                                gravity: ToastGravity.BOTTOM,
                                timeInSecForIosWeb: 1,
                                backgroundColor: Colors.black45,
                                textColor: Colors.white,
                                fontSize: 16.0
                            );
                          }
                        }else{
                          Fluttertoast.showToast(
                              msg: "保存失败",
                              toastLength: Toast.LENGTH_SHORT,
                              gravity: ToastGravity.BOTTOM,
                              timeInSecForIosWeb: 1,
                              backgroundColor: Colors.black45,
                              textColor: Colors.white,
                              fontSize: 16.0
                          );
                        }
                    },
                    )
                )
              ],
            )
          ],
        ),
    );
  }

  /*图片控件*/
  Widget _ImageView(tu) {
    if (tu == null) {
      return Center(
        child: Text("请选择图片或拍照"),
      );
    } else {
      if(!tu.toString().startsWith("tmp")){
        if(!tu.toString().startsWith("upload")){
          tu="tmp/"+tu;
        }
      }
      return Container(
        width: 75,
        height: 80,
        child: Stack(
          children: [
            Positioned(
              top: 10,
                child: Image.network(Config.getInstance().getHost()+tu,width: 70,height: 70,)
            ),
            Positioned(
              right: 1,
              top: 1,
              child: GestureDetector(
                child: Icon(Icons.highlight_off,color: Colors.red,size: 20,),
                onTap: (){
                  this.tu=null;
                  setState(() {

                  });
                },
              ),
            ),
          ],
        ),
      );
    }
  }

  //循环显示图片
  List<Widget> _ImageFor(value){
    List<Widget> x=[];
    List tus=value;
    for(int a=0;a<tus.length;a++){
      if(!tus[a].toString().startsWith("tmp")){
        if(!tus[a].toString().startsWith("upload")){
          tus[a]="tmp/"+tus[a];
        }
      }
      x.add(
          Container(
            width: 75,
            height: 80,
            child: Stack(
              children: [
                Positioned(
                    top: 10,
                    child: Image.network(Config.getInstance().getHost()+tus[a],width: 70,height: 70,)
                ),
                Positioned(
                  right: 1,
                  top: 1,
                  child: GestureDetector(
                    child: Icon(Icons.highlight_off,color: Colors.red,size: 20,),
                    onTap: (){
                      tus.removeAt(a);
                      setState(() {

                      });
                    },
                  ),
                ),
              ],
            ),
          )
      );
    }
    return x;
  }

}